// pages/paired_detail/paired_detail.js
const feedbackApi = require('../common/showToast.js');
const getToken = require('../../utils/get_token.js');
const formatTime = require('../../utils/util.js');
let openId, md = '', id = '',orderId='',goodId='', tuanId = '', orderSn = '', pageNo=1;
let cookie, token, accountInfo;
const ckToken = async (that) => {//token确认
  let nTime = Math.floor(new Date().getTime() / 1000);
  let oldTime = wx.getStorageSync('ntime') || 0;
  if (nTime < oldTime)//现在的时间小于到期时间
  {
    thou(that);
  } else {
    let tokens = await getToken.getToken();
    thou(that);
  }
}
const thou = (that) => {//token没有失效时执行的代码
  indexList(that);
  memList(that);
}
const remaind = (that,id) => {
  let params = ['shop/order/tipShip', {"memberId": md ,"orderSn":id }]
  getToken.getData(function (res) {
    console.log(res.data)
    feedbackApi.showToast({ title: '已提醒商家尽快发货', mask: false })//调用 showToast
  }, ...params)
};
const indexList = (that) => {
  let params;
  if (tuanId=='')
  {
    params = ['shop/order/get', { "orderSn": id }]
  }else{
    params = ['shop/pingTuan/getPinTuanMemberMsgNew', { "memberId": md, "memberOrderSn": id, "tuanId": tuanId,"openId":openId}]
  }
  getToken.getData(function (res) {
    console.log(res.data)
    let ds = res.data;
    let { x = ds.shipName, y = ds.shipMobile } = { x: ds.tzName, y: ds.tzMobile };//对象赋值 
    ds.tzName = x;
    ds.tzMobile = y;
    ds.tuanCommission = Number(ds.tuanCommission) / 100;
    that.data.tuaninco = ds.tuanCommission; 
    //福利金
    if (ds.tuanCommission > 0 && ds.seeType == 1) {
      if (ds.status == '交易成功') {
        that.data.cShow = true;
      } else {
        that.data.message = '*通知：拼团成功，可获得福利金￥' + ds.tuanCommission;
        that.data.nShow = true;
      }
    }
    if(ds.seeType==1)//是否是团长
    {
      that.data.sinfo='若退款完成,拼团自动解散,团员金额原路退还！';
      that.data.cinfo='团长申请退款完成,拼团解散,金额原路退还！';
    }else if(ds.seeType==0){
      that.data.sinfo='若退款完成,自动退出拼团,团员金额原路退还！';
      that.data.cinfo='申请退款完成，自动退出拼团，金额原路退还！';	
      if(ds.hadSubscribe>=1){//已经订阅过了
       that.data.dyinfo='已订阅到货提醒';
       that.data.actvShow=true;
      }	
    }
    //状态分类 退款分类
    if(ds.status=='待成团')
    {
     that.data.btnShow=1;
    }else if(ds.status=='待发货'||ds.status=='已发货'||ds.status=='待收货'){
      if(ds.seeType==1){//团长可以发起申请
        that.data.btnShow=4;
        }								
     }else if(ds.status=="申请退款")//申请退款中
     {
      ds.applyBackMsg=JSON.parse(ds.applyBackMsg);  
        if(ds.applyBackMsg.state=='60'||ds.applyBackMsg.state=='50')//退款中  
        {
          that.data.btnShow=3; 
        }else  if(ds.applyBackMsg.state=='61'){//退款完成
          that.data.btnShow=2;
        }
     }else if(ds.status=="退款完成"){//退款完成
        if(tuanId!='')
        {
          that.data.rfinfoShow=true;
        }
        that.data.btnShow=5;
        that.data.cinfo='团长申请退款完成,团员金额原路退还！';
     }else if(ds.status=="拒绝退款"){//退款失败
         that.data.btnShow=6;
     }
     if(ds.orderTypeCode=='ZTDD'&&ds.isOTA)//自提可以退货
     {
       if(ds.status=='待提货')
       {
        that.data.btnShow=7;
       }
     }
    if (ds.status == '待收货'||ds.status == '已发货' || ds.status == '同意退货' || ds.status == '交易成功') {//已发货
      if (ds.mailInfo!=null&&ds.mailInfo!= '')
      {
        ds.mailInfo=JSON.parse(ds.mailInfo);
        ds.mailInfo.data = ds.mailInfo.data||'';
        that.data.types = 1;
        if (ds.mailInfo.data!= '') {
          that.data.type = 1;
          ds.mailInfo.data=JSON.parse(ds.mailInfo.data);
        }
      }
    } else if (ds.status == "待发货") {
      that.data.type = 2;
    } else if (ds.status == "待成团") {
      that.data.type = 4;
    }
    that.data.gimg = 'https://www.globalhexi.com/' + ds.item[0].img;
    if (ds.item[0].guige != '' && ds.item[0].guige != null) {
      ds.item[0].guige = '规格:' + ds.item[0].guige;
    }
    ds.busLogo=`https://www.globalhexi.com/${ds.busLogo}`;    
    ds.item[0].img=`https://www.globalhexi.com/${ds.item[0].img}`;   
    wx.setStorageSync('wimg', ds.item[0].img);     
    ds.item[0].intPrice = `￥${(ds.item[0].intPrice / 100).toFixed(2)}`;
    ds.intRealPrice = (Number(ds.intRealPrice) / 100).toFixed(2);
    if (ds.isGroupBuy == '1')//自提
    {
      that.data.ztShow = true;
      if (ds.status == '交易成功' || ds.status == '已提货' || ds.status == '退款成功') {
        that.data.thShow = true;
      }
      if (ds.status == '待提货' || ds.status == '交易成功' || ds.status == '已提货' || ds.status == '退款成功') {
        if (ds.totalProductQuantity != '0') {
          that.data.ewmShow = true;
          if (tuanId == '') {
            ds.pickUpCode = ds.qrCode;
            ds.pickUpUrl = ds.qrCodeUrl;
            ds.ztName = ds.shipName;
            ds.ztMobile = ds.shipMobile;
            ds.ztAddress = ds.shipAddress;
          }
          if (ds.pickUpCode!=undefined)
          {
            var cl = ds.pickUpCode.length / 2;
            var str1 = ds.pickUpCode.substring(0, cl);
            var str2 = ds.pickUpCode.substring(cl, ds.pickUpCode.length);
            ds.str1 = str1;
            ds.str2 = str2;
          }
        }
      }
     }
    that.setData({
      dyinfo:that.data.dyinfo,
      actvShow:that.data.actvShow,
      sinfo:that.data.sinfo,
      cinfo:that.data.cinfo,
      btnShow:that.data.btnShow,
      rfinfoShow:that.data.rfinfoShow,
      type: that.data.type,
      types: that.data.types,
      tuaninco: that.data.tuaninco,
      message: that.data.message,
      cShow: that.data.cShow,
      nShow: that.data.nShow,
      ztShow: that.data.ztShow,
      thShow: that.data.thShow,
      ewmShow: that.data.ewmShow,
      s: ds
    })
  }, ...params)
};
const memList = (that) => {//团员列表
  let params = [ 'shop/pingTuan/getPinTuanOrderMemberViewList', {"memberId": md,"orderSn":id}]
  getToken.getData(function (res) {
    console.log(res.data)
    if(res.data.flag){
       let ds=res.data;
      for (let i = 0; i < ds.tuanMemberList.length; i++) {
        if (ds.tuanMemberList[i].state == 1) {
          ds.tuanMemberList[i].statt = '待付款';
        } else if (ds.tuanMemberList[i].state == 2) {
          ds.tuanMemberList[i].statt = '待成团';
        } else if (ds.tuanMemberList[i].state == 3) {         
            ds.tuanMemberList[i].statt = '待发货 ';      
        } else if (ds.tuanMemberList[i].state == 4) {
          ds.tuanMemberList[i].statt = '已发货';
        } else if (ds.tuanMemberList[i].state == 5) {//已收货
          ds.tuanMemberList[i].statt = '待评价';
        } else if (ds.tuanMemberList[i].state == 6) {
          ds.tuanMemberList[i].statt = '申请退款';
        }else if (ds.tuanMemberList[i].state == 7) {
          ds.tuanMemberList[i].statt = '退款退货成功';
        }
      }
      if(ds.tuanIndex==1){//团长
        let tlength=ds.tuanMemberList.length;
        let tindex=1;
        let tstate='';//团长的状态
        if(tlength==1){//只有团长一个人
          if(ds.tuanMemberList[0].state == 4){
            that.data.shuoShow=true;
          }
        }else if(tlength>1){//团中有多人
          for (let i = 0; i < tlength; i++) {
            if(ds.tuanMemberList[i].tuanIndex==1){//团长
              tstate=ds.tuanMemberList[i].state;
            }else{
              if (ds.tuanMemberList[i].state == 5) {
                  tindex++; 
                }
            }
          }
          if(tstate==4){//多人情况，只有团长状态为4时，通知按钮出现
              if(tindex==tlength)
             {
              that.data.shuoShow=true;
             }else{
              that.data.tzShow=true;
             } 
          }
        }
        let all = 0, aOll = [];
        all=ds.tuanMemberList.reduce(function(pre,cur){return cur.buyCount+pre },0)//获取总人数
        aOll = getImg(ds.tuanMemberList, aOll,10);//获取总头像数	  
        if (all <= 9) {
          that.data.more = false;
          forMore(that, aOll, 10);
        } else {
          forMore(that, aOll, 8);
        }
      }else{//团员确认收货
       that.data.shuoShow=ds.tuanMemberList[0].state==4?true:false;  
      }
      that.setData({
        tObj:ds,
        shuoShow:that.data.shuoShow,
        tzShow:that.data.tzShow,
        more:that.data.more
      })
    }
  }, ...params)
};
const likeList = (that) => {//猜你喜欢
  wx.showLoading({ title: '加载中', })
  let params = [ 'shop/pingTuan/guessYouLike', {"openId": openId ,"memberId": md,"pageSize": pageNo,"seeType":2,"pinTuanGoodsId": id,"orderSn":""}]
  getToken.getData(function (res) {
    console.log(res.data)
    let data = res.data;
    if (data.rows.length > 0) {
      for (let i = 0; i < data.rows.length; i++) {
        data.rows[i].goodsImageStore = JSON.parse(data.rows[i].goodsImageStore);
        data.rows[i].img = 'http://www.globalhexi.com/' + data.rows[i].goodsImageStore[0].path + '/small/' + data.rows[i].goodsImageStore[0].id + '.jpg';
        data.rows[i].intPinPrice = (data.rows[i].intPinPrice / 100).toFixed(2);
        data.rows[i].intPrice = (data.rows[i].intPrice / 100).toFixed(2);
        that.data.lkList.push(data.rows[i]);
      }
    }
    if (pageNo == 1) {
      if (data.rows.length > 0) {
        that.data.likeShow = true;
      } else {
        that.data.likeShow = false;
      }
    }
    setTimeout(function () {
      wx.hideLoading();
    }, 500)
    that.setData({
      lkList: that.data.lkList,
      likeShow: that.data.likeShow,
      hidden: true
    })
  }, ...params)

};
const getImg = function (d, all,t) {//取头像数组
  let dLength=d.length;
  let aNum=0;
  for (let i = 0; i < dLength; i++) {
    for (let j = 0; j < d[i].buyCount; j++) {
      all.push(d[i].memberLogo);
      aNum++;
      if(aNum>=t){
        break;
      }
    }
  }
  return all;
}
const forMore = function (that, data, t) {
  for (let i = 0; i < data.length; i++) {
    if(data[i].match(/http/g)){

    }else{
      if (data[i].match(/hexishop/g)) {
        data[i] = 'https://www.globalhexi.com/upload/head/default.png';
      }else{
        data[i]='https://www.globalhexi.com/'+data[i];
      }
    }
    if (i < t) {
      that.data.aList.push({ 'img': data[i], 'show': true })
    } else {
      that.data.aList.push({ 'img': data[i], 'show': false })
    }
  }
  that.setData({
    aList: that.data.aList
  })
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type:0,
    types:0,
    boolT:true,
    shuoShow:false,
    tzShow:false,
    likeShow:false,
    nShow:false,
    cShow:false,
    more: true,
    btnShow:0,
    refundShow:false,
    ztreduShow:false,
    rfinfoShow:false,
    shShow:true,
    sinfo:'若退款完成,拼团自动解散,团员金额原路返回。',
    cinfo:'团长申请退款完成,拼团解散,金额原路退还！',
    dyinfo:'到货提醒',
    actvShow:false,
    ztShow:false,
    ewmShow:false,
    thShow:false,
    tuaninco:0,
    message:'',
    gimg:"",
    lkList: [],
    aList:[],
    s:{},
    tObj:{}

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that=this;
    id = options.id;//团员订单号
    goodId=options.god;
    console.log(options)
    tuanId = options.tuanId||'';
    orderId =options.aordersn ;//团长订单号
    md = wx.getStorageSync('memberId') || '';
    openId = wx.getStorageSync('openId') || '';
    cookie = wx.getStorageSync('cookie') || '';
    token = wx.getStorageSync('token') || '';
    pageNo=1;
    accountInfo = wx.getAccountInfoSync();
    ckToken(that);
  },
  go_logis:function(e){
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.navigateTo({
        url: '../logistics/logistics?id=' + orderId,
        success: function () {
          setTimeout(function () {
            that.data.boolT = true;
          }, 500)
        }
      })
    }
  },
  remind:function(e){//提醒发货
    let that = this;
    let txState = wx.getStorageSync('txState') || '';
    if(txState!='ok'){
      wx.requestSubscribeMessage({
        tmplIds: ['U_wO9UeN7Ic4Bli2OSZBNy8JwNG7BPmeRU0GliKBA2U'],
        success (res) { 
          console.log(res)
          if(res['U_wO9UeN7Ic4Bli2OSZBNy8JwNG7BPmeRU0GliKBA2U']=='accept'){
            let params = [ 'gift/messagePush/subscribeNoticeOfOrder', {"useType":15,"memberId": md,"orderSn":orderId,"memberOrderSn":id,"appId":accountInfo.miniProgram.appId,"openId":openId}]
            getToken.getData(function (res) {
              console.log(res.data)
              if(res.data.flag){
                wx.setStorageSync('txState', 'ok');
              }
            }, ...params) 
          }
        }
      })
    }
    let id = e.currentTarget.dataset.id;
    remaind(that, id);
  },
  go_dh:function(e){//到货提醒按钮
    let that = this;
    if(that.data.s.hadSubscribe==0){
      wx.requestSubscribeMessage({
        tmplIds: ['R04TYj328b0cr0-e6bMlD6vRyo-p76PzKKG0vp_GYpU'],
        success (res) { 
          if(res['R04TYj328b0cr0-e6bMlD6vRyo-p76PzKKG0vp_GYpU']=='accept'){
            let params = [ 'gift/messagePush/subscribeNoticeOfOrder', {"useType":14,"memberId": md,"orderSn":orderId,"memberOrderSn":id,"appId":accountInfo.miniProgram.appId,"openId":openId}]
            getToken.getData(function (res) {
              console.log(res.data)
              if(res.data.flag){            
                that.setData({
                  dyinfo:'已订阅到货提醒',
                  actvShow:true
                })
              }else{
                feedbackApi.showToast({ title:res.data.message, mask: false })//调用 showToast
              }
            }, ...params) 
          }
        }
      })
    }
  },
  sgood:function(e){//收货按钮
    let that = this;
    wx.showLoading({ title: '加载中', })
    let params = [ 'shop/order/yesTuanYuanOrder', {"memberId": md,"orderSn":id}]
    getToken.getData(function (res) {
      console.log(res.data)
      if(res.data.flag){
        feedbackApi.showToast({ title: '确认收货成功', mask: false })//调用 showToast
        memList(that);
      }else{
        feedbackApi.showToast({ title:res.data.message, mask: false })//调用 showToast
      }
      setTimeout(function () {wx.hideLoading();}, 500)
    }, ...params)
  },
  notice:function(e){//团长通知团员取货
    let that = this;
    wx.showModal({
      title: '消息发送确认',
      content: '系统将自动向已订阅取货通知的团员发送消息，请随时关注团员取货消息，消息仅发送一次',
      confirmText:'发送消息',
      success (res) {
        if (res.confirm) {
          let params = [ 'gift/messagePush/subscribeNoticeOfOrder', {"useType":13,"memberId": md,"orderSn":orderId,"memberOrderSn":id,"appId":accountInfo.miniProgram.appId,"openId":openId}]
          getToken.getData(function (res) {
            console.log(res.data)
            if(res.data.flag){
              that.data.s.hadSubscribe=1;
              that.setData({s:that.data.s})
              feedbackApi.showToast({ title: '通知消息发送成功', mask: false })//调用 showToast 
            }
          }, ...params)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  enter: function (e) {
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.redirectTo({
        url: '../paired_detail/paired_detail?scene=' + e.currentTarget.dataset.id,
        success: function () {
          setTimeout(function () {
            that.data.boolT = true;
          }, 500)
        }
      })
    }
  },
  rfdt:function(){//查看退款进度
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.navigateTo({
        url: `../rdt/rdt?orderSn=${id}&tuanId=${tuanId}`, 
        success: function () {
          setTimeout(function () {that.data.boolT = true;}, 500)
        }
      })
    }

  },
  goRefund:function(){//已成团退款事件
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.navigateTo({
        url: `../refund/refund?id=${id}&price=${that.data.s.intRealPrice}&tuanId=${tuanId}`,
        success: function () {
          setTimeout(function () {that.data.boolT = true;}, 500)
        }
      })
    }
  },
  refund:function(e){//待成团申请退款
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      that.setData({
        refundShow: true
      })
      setTimeout(function () {that.data.boolT = true;}, 500)
    }
  },
  rfCancel:function(e){//待成团申请退款按钮取消
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      that.setData({
        refundShow: false
      })
      setTimeout(function () {that.data.boolT = true;}, 500)
    }
  },
  rfSure:function(e){//待成团申请退款按钮
    let that = this;
    let params = [ 'shop/pinTuanPay/applyBackPinTuanMemberMoney', {"tuanId":tuanId,"memberId":md,"orderSn":id}]
    getToken.getData(function (res) {
      if(res.data.flag){
        that.data.refundShow=false;
        that.data.rfinfoShow=true;
        that.data.shShow=false;
        that.data.btnShow=5;
        that.data.s.status='退款完成';
        that.setData({
          refundShow: that.data.refundShow,
          rfinfoShow: that.data.rfinfoShow,
          shShow: that.data.shShow,
          s: that.data.s,
          btnShow: that.data.btnShow,
        })
      }
    }, ...params)
  },
  ztRefund:function(e){//自提申请退款
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      that.setData({
        ztreduShow: true
      })
      setTimeout(function () {that.data.boolT = true;}, 500)
    }
  },
  ztCancel:function(e){//自提申请退款按钮取消
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      that.setData({
        ztreduShow: false
      })
      setTimeout(function () {that.data.boolT = true;}, 500)
    }
  },
  ztSure:function(e){//自提申请退款按钮

  },
  launchAppError(e) {
    console.log(e)
  },
  /**
* 页面上拉触底事件的处理函数
*/
  onReachBottom: function () {
    let that = this;
    pageNo++;
    //likeList(that);

  },
  /**
  * 用户点击右上角分享
  */
  onShareAppMessage: function (res) {
    let that = this;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res)
    }
    let sinfo=that.data.s.item[0];
    let tit='【仅剩' + sinfo.lastNum + '个】我' + sinfo.price + '元拼了' + sinfo.name;
    return {
      title: tit,
      imageUrl:that.data.s.item[0].img, 
      path: '/pages/tuxedo/tuxedo?id=' + goodId + '&tuanid=' + tuanId,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  }
})